﻿//using System;
//using System.Collections.Generic;
//using System.Text;
//using NHibernate;
//using NHibernate.Cfg;

//namespace DBServer
//{
//    public class NHibernateHelper
//    {
//        private static ISessionFactory sessionFactory;

//        static NHibernateHelper()
//        {
//            sessionFactory = new Configuration().Configure().BuildSessionFactory();
//        }

//        public static ISession GetSession()
//        {
//            return sessionFactory.OpenSession();
//        }
//    }
//}


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;

using NHibernate.Cfg;
using NHibernate;
using NHibernate.Engine;

namespace DBServer
{
    public static class NHibernateHelper
    {
        #region For data operation

        /// <summary>
        /// The singleton Sessionfactory
        /// </summary>
        private static NHibernate.ISessionFactory SessionFactory = null;

        /// <summary>
        /// The configuration file name
        /// </summary>
        private static string ConfigFileName = "hibernate.cfg.xml";

        /// <summary>
        /// Gets the sessionfactory
        /// </summary>
        /// <param name="assemblyName">Application assembly name ,configuration will search the objects in the assembly</param>
        /// <returns></returns>
        private static ISessionFactory GetSessionFactory(string assemblyName)
        {
            if (SessionFactory != null)
            {
                return SessionFactory;
            }
            NHibernate.Cfg.Configuration Cfg = null;
            try
            {
                Cfg = new Configuration().Configure(ConfigFileName);
            }
            catch (Exception e)
            {
                NHibernate.HibernateException ex = new HibernateException(e);
                throw (ex);
            }
            if (assemblyName != null)
            {
                System.Reflection.Assembly aa = System.Reflection.Assembly.Load(assemblyName);
                Cfg.AddAssembly(aa);
            }
            try
            {
                SessionFactory = Cfg.BuildSessionFactory();
                return SessionFactory;
            }
            catch (Exception e)
            {
                NHibernate.HibernateException ex = new HibernateException(e);
                throw (ex);
            }
        }

        /// <summary>
        /// Another method of gets sessions
        /// </summary>
        /// <returns></returns>
        private static ISessionFactory GetSessionFactory()
        {
            return GetSessionFactory(null);
        }

        /// <summary>
        /// Get session
        /// </summary>
        /// <returns></returns>
        public static ISession CurrentSession()
        {
            ISessionFactory factory = GetSessionFactory();
            try
            {
                ISession Session = factory.OpenSession();
                return Session;
            }
            catch (Exception e)
            {
                NHibernate.HibernateException ex = new HibernateException(e);
                throw (ex);
            }
        }

        /// <summary>
        /// Reload configuration
        /// </summary>
        public static void ReloadConfig()
        {
            SessionFactory = null;
        }

        ///// <summary>
        ///// Use Hibernate to execute SQL statment
        ///// </summary>
        ///// <param name="query"></param>
        ///// <returns></returns> IList
        //public static System.Collections.IList ExecuteSQL(string query)
        //{
        //    System.Collections.IList result = new ArrayList();

        //    ISessionFactoryImplementor s = (ISessionFactoryImplementor)GetSessionFactory();
        //    IDbCommand cmd = s.ConnectionProvider.Driver.CreateCommand();
        //    cmd.CommandText = query;

        //    IDbConnection conn = s.OpenConnection();
        //    try
        //    {
        //        cmd.Connection = conn;
        //        IDataReader rs = cmd.ExecuteReader();

        //        while (rs.Read())
        //        {
        //            int fieldCount = rs.FieldCount;
        //            object[] values = new Object[fieldCount];
        //            for (int i = 0; i < fieldCount; i++)
        //            {
        //                values[i] = rs.GetValue(i);
        //            }
        //            result.Add(values);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        NHibernate.HibernateException ex = new HibernateException(e);
        //        throw (ex);
        //    }
        //    finally
        //    {
        //        s.CloseConnection(conn);
        //    }
        //    return result;
        //}

        /// <summary>
        /// Saves an object to DB
        /// </summary>
        /// <param name="obj"></param>
        public static int SaveObject(Object obj)
        {
            ISession session = CurrentSession();
            ITransaction tr = session.BeginTransaction();
            try
            {
                session.Save(obj);
                tr.Commit();
                return 1;
            }
            catch (Exception ex)
            {
                tr.Rollback();
                return 0;
                //throw (ex);
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Close();
                }
            }
        }

        /// <summary>
        /// Update an object to DB
        /// </summary>
        /// <param name="obj"></param>
        public static int UpdateObject(Object obj)
        {
            ISession session = CurrentSession();
            ITransaction tr = session.BeginTransaction();
            try
            {
                session.Update(obj);
                tr.Commit();
                return 1;
            }
            catch (Exception ex)
            {
                tr.Rollback();
                return 0;
                //throw (ex);
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Close();
                }
            }
        }

        /// <summary>
        /// SaveOrUpdate an object to DB
        /// </summary>
        /// <param name="obj"></param>
        public static int SaveOrUpdateObject(Object obj)
        {
            ISession session = CurrentSession();
            ITransaction tr = session.BeginTransaction();
            try
            {
                session.SaveOrUpdate(obj);
                tr.Commit();
                return 1;
            }
            catch (Exception ex)
            {
                tr.Rollback();
                //throw (ex);
                return 0;
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Close();
                }
            }
        }
        /// <summary>
        /// Delete an object
        /// </summary>
        /// <param name="obj"></param>
        public static int DeleteObject(Object obj)
        {
            ISession session = CurrentSession();
            ITransaction tr = session.BeginTransaction();
            try
            {
                session.Delete(obj);
                tr.Commit();
                return 1;
            }
            catch (Exception ex)
            {
                tr.Rollback();
                return 0;
                //throw (ex);
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Close();
                }
            }
        }

        /// <summary>
        /// Find  by HQL
        /// </summary>
        /// <param name="obj"></param>
        public static System.Collections.IList Find(string HQL)
        {
            ISession session = CurrentSession();
            System.Collections.IList list = null;
            try
            {
                list = session.Find(HQL);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Close();
                }
            }
            return list;
        }

        /// <summary>
        /// To get the specify  object from DB
        /// </summary>
        /// <param name="ClassType"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Object GetObject(Type ClassType, object ID)
        {
            ISession session = CurrentSession();
            object Getobj = null;
            try
            {
                Getobj = session.Get(ClassType, ID);
                return Getobj;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (session.IsOpen)
                {
                    session.Close();
                }
            }

        }

        /// <summary>
        /// To see whether an object exists
        /// </summary>
        /// <param name="ClassType"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ObjExist(Type ClassType, object ID)
        {
            object Getobj = GetObject(ClassType, ID);
            if (Getobj == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region For making hbm2ddl

        /// <summary>
        /// DDL file path
        /// </summary>
        private static string DllOutPutPath = @"D://HbmDDL.txt";

        /// <summary>
        /// Configuration file name
        /// </summary>
        private static string DllMappingFile = "hibernate.cfg.xml";
        /// <summary>
        /// Make DDL file
        /// </summary>
        /// <param name="hbmConfigurationfile">The hbm configuration file</param>
        public static void MakeDDL(string hbmConfigurationfile)
        {
            if (!System.IO.File.Exists(hbmConfigurationfile))
            {
                return;
            }
            NHibernate.Cfg.Configuration Cfg = null;
            try
            {
                Cfg = new Configuration().Configure(hbmConfigurationfile);
            }
            catch (Exception e)
            {
                throw new HibernateException(e);
            }
            NHibernate.Tool.hbm2ddl.SchemaExport schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(Cfg);
            schemaExport.SetOutputFile(DllOutPutPath);
            schemaExport.Create(false, false);
            //schemaExport.Execute(false, false, false, false);
        }
        /// <summary>
        /// Make DDL file
        /// </summary>
        public static void MakeDDL()
        {
            MakeDDL(DllMappingFile);
        }
        #endregion
    }
}